package feeinterface.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.ulwx.database.DataBaseSet;
import com.ulwx.database.DbException;
import com.ulwx.tool.DbUtils;
import com.ulwx.tool.ObjectUtils;
import com.ulwx.tool.StringUtils;

import feeinterface.modeldb.ChannelTest;


/**
 * 通道测试表
 * 
 * @author 黄杰
 * 
 */
public class ChannelTestDao {
	private static final Logger log = Logger.getLogger(ChannelTestDao.class);
	/**
	 * 通过IMSI，手机号码和合作ID获取通道指令
	 * 
	 * 是否配置了测试绑定
	 * @param imsi
	 * @param phone
	 * @param coid
	 * @return
	 * @throws DbException
	 */
	public static List<ChannelTest> getTestDataBy(String imsi, String phone,
			Integer coid) throws DbException {
		
		try {
			String sql="SELECT * FROM ChannelTest WHERE ";
			String selectGroupIDSQL = "SELECT GroupID FROM ChannelTest WHERE  ";
			int i=0;
			Map<Integer, Object> args = new HashMap<Integer, Object>();
			String where="";
			if(coid>0){
				where= where+"AND ServiceCoID=?";
				args.put(i++, coid);
			}
			if(StringUtils.hasText(imsi) && StringUtils.hasText(phone)){
				where=where+" AND (IMSI =? OR Phone =?)";
				args.put(i++, imsi);
				args.put(i++, phone);
			}else if(StringUtils.hasText(imsi) && !StringUtils.hasText(phone)){
				where=where+" AND IMSI =?";
				args.put(i++, imsi);
			}else if(!StringUtils.hasText(imsi) && StringUtils.hasText(phone)){
				where=where+" AND Phone =?";
				args.put(i++, phone);
			}
			where =StringUtils.trim(where);
			if(StringUtils.isEmpty(where)){
				return null;
			}
			
			//#########找出最新的绑定的GroupID
			String GroupID = null;
			selectGroupIDSQL = selectGroupIDSQL + StringUtils.trimLeadingString(where, "AND") + 
					" ORDER BY UpdateTime desc LIMIT 1";
			DataBaseSet set = DbUtils.doCachedQuery(null, selectGroupIDSQL, args);
			if(set.next()){
				GroupID = set.getString("GroupID");
			}else{
				return null;
			}
			
			sql=sql+StringUtils.trimLeadingString(where, "AND") + " AND GroupID = ?";
			args.put(i, GroupID);
			List<ChannelTest> list = DbUtils.doQueryClass(null,ChannelTest.class,
					sql, args);
			if(list.size()==0)
				return null;
			return list;
			
		} catch (Exception e) {
			log.error("",e);
			
		}
		return null; 

	}
	
	public static void test()throws Exception{
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT * FROM ChannelTest WHERE  ServiceCoID is ?");
		Map<Integer, Object> args = new HashMap<Integer, Object>();
		args.put(1, null);
	
		List<ChannelTest> db = DbUtils.doQueryClass(null, ChannelTest.class, sb.toString(), args);
		System.out.println(ObjectUtils.toJsonString(db));
	}
	
	public static void main(String[] args) throws Exception{
		//test();
		getTestDataBy("460022259306941","",10015);
	}
}
